package com.zhu.esyblog.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhu.esyblog.Utils.TokenUtils;
import com.zhu.esyblog.mapper.SysUserMapper;
import com.zhu.esyblog.pojo.RespBean;
import com.zhu.esyblog.pojo.SysUser;
import com.zhu.esyblog.service.ISysUserService;
import com.zhu.esyblog.service.LoginService;
import com.zhu.esyblog.vo.LoginParams;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional //事务注解
public class LoginServiceImpl implements LoginService {
    private static  final String salt="123456!@#";
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public RespBean login(LoginParams loginParams) {
        /**
         * 1.检查参数是否合法
         */
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        password= DigestUtils.md5Hex(password+salt);
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(password)){
            return RespBean.success("参数不合法",10001);

        }


        /**
         * 根据用户名和密码查询user表
         */
     SysUser user=sysUserService.findUser(account,password);
     if(user==null){
         return RespBean.error("用户名或密码错误",10002);
     }
        /**
         * 生成token
         */
        String token = TokenUtils.createToken(user.getId());
        /**
         * token放入redis中
         */
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return RespBean.success("success",token);



    }

    /**
     * 检验token
     * @param token
     * @return
     */
    @Override
    public SysUser checkToken(String token) {
        Map<String, Object> map = TokenUtils.checkToken(token);
        if(map==null){
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if(StringUtils.isEmpty(userJson)){
            return null;
        }
        SysUser user = JSON.parseObject(userJson, SysUser.class);

        return user;
    }

    /**
     * 注销
     * @param token
     * @return
     */
    @Override
    public RespBean logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return RespBean.success("success",null);
    }

    /**
     * 注册
     * @param loginParams
     * @return
     */
    @Override
    public RespBean register(LoginParams loginParams) {
        /**
         *  判断参数是否合法
         *  判断账户是否存在，存在给返回账户已经被注册
         *  不存在，注册用户
         *  返回token，存入redis 返回
         *  加上事务，一旦发生故障事务回滚
         */
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        String nickname = loginParams.getNickname();
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(password)||StringUtils.isEmpty(nickname)){
            return RespBean.error("请输入必填项",10001);
        }
       SysUser user=sysUserService.findUserByAccount(account);
        if(user!=null){
            return RespBean.error("账号太受欢迎，请更换！",10002);
        }
        user=new SysUser();
        user.setNickname(nickname);
        user.setAccount(account);
        user.setPassword(DigestUtils.md5Hex(password+salt));
        user.setCreateDate(System.currentTimeMillis());
        user.setLastLogin(System.currentTimeMillis());
        user.setAvatar("/static/img/logo.b3a48c0.png");
        user.setAdmin(true);
        user.setDeleted(false);
        user.setSalt("");
        user.setStatus("");
        user.setEmail("");
        sysUserService.save(user);
        String token = TokenUtils.createToken(user.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token,JSON.toJSONString(user),1,TimeUnit.DAYS);
        return RespBean.success("success",token);
    }
}
